//
// CompressedResource.cpp
//

#include "CompressedResource.h"

bool CCompressedResource::open(const wchar_t *pwszFileName)
{
	if(pwszFileName == NULL) return false;
	if(_pArchive != NULL) close();

	char buf[260];
	if(_snprintf(buf, 260, "%S", pwszFileName) <= 0) return false;
	_pArchive = unzOpen(buf);
	
	if(_pArchive == NULL) return false;
	return true;
}

void CCompressedResource::close(void)
{
	if(_pArchive) {
		unzClose(_pArchive);
		_pArchive = NULL;
	}
}

size_t CCompressedResource::getCurrentFileSize(void)
{
	if(_pArchive && unzOpenCurrentFile(_pArchive) == UNZ_OK) {
		unz_file_info info;
		unzGetCurrentFileInfo(_pArchive, &info, NULL, 0, NULL, 0, NULL, 0);
		unzCloseCurrentFile(_pArchive);
		return info.uncompressed_size;
	}
	return 0;
}

size_t CCompressedResource::getSize(const wchar_t *pwszLocation)
{
	if(pwszLocation == NULL || _pArchive == NULL) return 0;

	char buf[260];
	if(_snprintf(buf, 260, "%S", pwszLocation) <= 0) return 0;
	if(unzLocateFile(_pArchive, buf, 0) == UNZ_OK) return getCurrentFileSize();
	return 0;
}

int CCompressedResource::fetchCurrentFile(BYTE *pBuffer, size_t uBufferSize)
{
	if(pBuffer == NULL || _pArchive == NULL) return -1;

	size_t recvbyte;
	if(unzOpenCurrentFile(_pArchive) == UNZ_OK) {
		recvbyte = unzReadCurrentFile(_pArchive, (void *)pBuffer, uBufferSize);
		unzCloseCurrentFile(_pArchive);
		return recvbyte;
	}
	return -1;
}

int CCompressedResource::fetch(const wchar_t *pwszLocation, BYTE *pBuffer, size_t uBufferSize)
{
	if(pwszLocation == NULL || _pArchive == NULL) return -1;

	char buf[260];
	if(_snprintf(buf, 260, "%S", pwszLocation) <= 0) return false;
	if(unzLocateFile(_pArchive, buf, 0) == UNZ_OK) return fetchCurrentFile(pBuffer, uBufferSize);
	return -1;
}

bool CCompressedResource::locateFile(const wchar_t *pwszLocation)
{
	char buf[260];
	if(_snprintf(buf, 260, "%S", pwszLocation) <= 0) return false;
	if(unzLocateFile(_pArchive, buf, 0) == UNZ_OK) return true;
	return false;
}